import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.SocketException;

/**
 * Recebe uma string de um socket multicast e imprime na tela
 *
 */
public class MultiClient  extends Thread {

	private String destinationGroup;
	
	InetAddress ia;
	int port = 0;
	
	public MultiClient (String destinationGroup, String destinationPort) throws Exception {
		this.destinationGroup = destinationGroup;
		
		try {
			ia = InetAddress.getByName(destinationGroup);
			port = Integer.parseInt(destinationPort);
		} catch (Exception e) {
			System.err.println("Erro nos parâmetros: " + e.getMessage());
			e.printStackTrace();
			throw e;
		}
	}
	
	public void run () {
		try {
			MulticastSocket ms = new MulticastSocket(port);
			ms.joinGroup(ia);
			
			while(true) {
			    byte[] buffer = new byte[65509];
			    DatagramPacket dp = new DatagramPacket(buffer, buffer.length);

				ms.receive(dp);
				String message = new String (dp.getData());
				System.out.println("Mensagem recebida do grupo " + destinationGroup + " porta " + port + " conteudo = [" + message + "]");
			}

		} catch (SocketException se) {
			System.err.println(se);
		} catch (IOException ie) {
			System.err.println(ie);
		}	
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {		
		try {
			MultiClient counter = new MultiClient("224.5.5.1", "27000");
			counter.start();
			counter.join(); 
		} catch (InterruptedException e) {
			System.out.println("Finalizando execução...");
		} catch (Exception e) {
			System.err.println("Erro no envio de pacotes multicast. Mensage = " + e.getMessage());
			e.printStackTrace();
		}
	}

}
